<template>
    <div class="page-list">
        <t-card title="页面管理" bordered>
            <!-- 顶部操作按钮 -->
            <t-button theme="primary" size="medium" @click="handleCreate">
                新建页面
            </t-button>

            <!-- 表格 -->
            <t-table
                    :data="pageList"
                    :columns="columns"
                    :loading="loading"
                    row-key="id"
                    bordered
                    hover
            />

            <!-- 分页 -->
            <div class="pagination" v-if="total > 0">
                <t-pagination
                        :total="total"
                        :page-size="pageSize"
                        :current="pageNum"
                        @change="onPageChange"
                        @page-size-change="onPageSizeChange"
                />
            </div>
        </t-card>

        <!-- 编辑 / 新建弹框 -->
        <t-dialog
                v-model:visible="showEditDialog"
                header="页面信息"
                confirm-btn="保存"
                cancel-btn="取消"
                @confirm="handleSaveEdit"
        >
            <t-form :data="editForm" label-width="100" label-align="right">
                <t-form-item label="页面Key">
                    <t-input v-model="editForm.pageKey" placeholder="请输入页面Key" />
                </t-form-item>
                <t-form-item label="标题">
                    <t-input v-model="editForm.title" placeholder="请输入标题" />
                </t-form-item>
                <t-form-item label="描述">
                    <t-textarea v-model="editForm.description" placeholder="请输入描述" />
                </t-form-item>
            </t-form>
        </t-dialog>
    </div>
</template>

<script setup>
    import { ref, onMounted, reactive } from 'vue'
    import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
    import PageService from '../api/page'
    import router from "../router";

    // ========================= 编辑弹框 & 数据 =========================
    const showEditDialog = ref(false)
    const editForm = reactive({
        id: null,
        pageKey: '',
        title: '',
        description: '',
    })

    // ========================= 分页 & 表格数据 =========================
    const pageList = ref([])
    const loading = ref(false)
    const total = ref(0)
    const pageSize = ref(10)
    const pageNum = ref(1)

    // ========================= 表格列 =========================
    const handleEdit = (row) => {
        Object.assign(editForm, row)
        showEditDialog.value = true
    }

    const handleDesigner = (row) => {
        // 跳转到 /designer，并携带 id 参数
        router.push({
            path: '/designer',
            query: { id: row.id }
        });
    }

    const handleComponent = (row) => {
        // 跳转到 /designer，并携带 id 参数
        router.push({
            path: '/components',
            query: { pageId: row.id }
        });
    }

    const handlePublish = (row) => {
        const confirmDialog = DialogPlugin.confirm({
            header: '确认发布',
            body: `是否确认发布页面「${row.title}」？`,
            confirmBtn: '确定',
            cancelBtn: '取消',
            onConfirm: async () => {
                try {
                    await PageService.publishPage(row.id)
                    MessagePlugin.success('发布成功')
                    fetchPageList()
                } catch (e) {
                    console.error(e)
                    MessagePlugin.error('发布失败')
                } finally {
                    confirmDialog.destroy()
                }
            },
        })
    }

    const columns = [
        { colKey: 'id', title: 'ID', width: 60 },
        { colKey: 'pageKey', title: '页面Key', width: 120 },
        { colKey: 'title', title: '标题' },
        { colKey: 'description', title: '描述' },
        { colKey: 'status', title: '状态', width: 100 },
        { colKey: 'version', title: '版本', width: 80 },
        { colKey: 'createdAt', title: '创建时间', width: 180 },
        { colKey: 'updatedAt', title: '更新时间', width: 180 },
        {
            colKey: 'op',
            title: '操作',
            width: 220,
            cell: (h, { row }) => [
                h(
                    't-button',
                    {
                        size: 'small',
                        theme: 'primary',
                        onClick: () => handleEdit(row),
                        style: 'margin-right: 8px;',
                    },
                    '编辑'
                ),
                h(
                    't-button',
                    {
                        size: 'small',
                        theme: 'success',
                        onClick: () => handleDesigner(row),
                        style: 'margin-right: 8px;',
                    },
                    '制作'
                ), h(
                    't-button',
                    {
                        size: 'small',
                        theme: 'success',
                        onClick: () => handleComponent(row),
                        style: 'margin-right: 8px;',
                    },
                    '组件管理'
                ),
                h(
                    't-button',
                    {
                        size: 'small',
                        theme: 'success',
                        onClick: () => handlePublish(row),
                    },
                    '发布'
                ),
            ],
        },
    ]

    // ========================= 新建页面 =========================
    const handleCreate = () => {
        Object.assign(editForm, {
            id: null,
            pageKey: '',
            title: '',
            description: '',
        })
        showEditDialog.value = true
    }

    // ========================= 保存（新增/编辑） =========================
    const handleSaveEdit = async () => {
        try {
            if (!editForm.pageKey || !editForm.title) {
                MessagePlugin.warning('页面Key和标题不能为空')
                return
            }

            let res
            if (editForm.id) {
                // 编辑已有页面
                res = await PageService.updatePage(editForm.id, {
                    pageKey: editForm.pageKey,
                    title: editForm.title,
                    description: editForm.description,
                })
            } else {
                // 新建页面
                res = await PageService.createPage({
                    pageKey: editForm.pageKey,
                    title: editForm.title,
                    description: editForm.description,
                    schemaJson: '{}', // 初始化空布局
                })
            }

            if (res.code === 0) {
                MessagePlugin.success(editForm.id ? '保存成功' : '创建成功')
                showEditDialog.value = false
                fetchPageList()
            } else {
                MessagePlugin.error(res.data?.message || (editForm.id ? '保存失败' : '创建失败'))
            }
        } catch (e) {
            console.error(e)
            MessagePlugin.error(editForm.id ? '保存出错' : '创建出错')
        }
    }

    // ========================= 数据加载 & 分页 =========================
    const fetchPageList = async () => {
        loading.value = true
        try {
            const res = await PageService.getAllPages({ pageNum: pageNum.value, pageSize: pageSize.value })
            const data = res.data.data || res.data
            pageList.value = data.records || data
            total.value = data.total || pageList.value.length
        } catch (e) {
            console.error(e)
            MessagePlugin.error('获取页面数据失败')
        } finally {
            loading.value = false
        }
    }

    onMounted(fetchPageList)

    const onPageChange = (page) => {
        pageNum.value = page.current
        fetchPageList()
    }

    const onPageSizeChange = (size) => {
        pageSize.value = size
        fetchPageList()
    }
</script>

<style scoped>
    .page-list {
        padding: 20px;
        background-color: #f5f5f5;
        min-height: calc(100vh - 64px);
    }

    .pagination {
        display: flex;
        justify-content: flex-end;
        margin-top: 16px;
    }
</style>
